package com.yang.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.*;
import java.util.Map;

/**
 * Created by EDZ on 2020/8/11.
 */
@Slf4j
public class HttpUtil {

    /**
     * 请求post
     *
     * @param url
     * @param data
     * @return
     */
    public static InputStream sendPost(String url, String data) {
        OutputStreamWriter out = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);

            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(data);
            out.flush();
            return conn.getInputStream();
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！ e = {} ", e);
        }finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 微信请求 (需要带证书)
     * @param xmlObj
     * @param url
     * @param wxHchid
     * @param p12Url
     * @return
     */
    public static String sendPost(String url,String xmlObj,String wxHchid,String p12Url){
        String responseString = null;
        try (InputStream systemResourceAsStream = new FileInputStream(new File(p12Url))) {
            HttpRequest httpRequest=new HttpRequest(systemResourceAsStream,wxHchid);
            responseString = httpRequest.sendPost(url, xmlObj);
            log.info("【退款请求】 返回结果 : {} ", responseString);

        }catch (Exception e) {
            log.error("【退款请求】 出现异常 : {}",e);
        }
        return responseString;
    }


    public static  String sendPost(String url, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            conn =(HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if(param.length()>0){
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    //System.out.println(entry.getKey()+":"+entry.getValue());
                }
                //System.out.println("param:"+param.toString());
                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if (conn != null) {
                    conn.disconnect();
                }
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath
     */
    public static  byte[] netImageToBase64(String netImagePath) {
        byte[] strNetImageToBase64 = null;
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 对字节数组Base64编码
            strNetImageToBase64 = data.toByteArray();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return strNetImageToBase64;
    }
}
@Slf4j
class HttpRequest {

    public interface ResultListener {
        public void onConnectionPoolTimeoutError();
    }
    /**
     * 连接超时时间，默认10秒
     */
    private int socketTimeout = 10000;
    /**
     * 传输超时时间，默认30秒
     */
    private int connectTimeout = 30000;

    /**
     * 请求器的配置
     */
    private RequestConfig requestConfig;
    /**
     * HTTP请求器
     */
    private CloseableHttpClient httpClient;

    public HttpRequest(InputStream instream,String passwd) {
//		this.pathName = pathName;
        try {
            init(instream,passwd);
        } catch (UnrecoverableKeyException e) {

            e.printStackTrace();
        } catch (KeyManagementException e) {

            e.printStackTrace();
        } catch (KeyStoreException e) {

            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    private void init(InputStream instream,String passwd) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
            KeyManagementException {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try {
            // 设置证书密码
            keyStore.load(instream, passwd.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
        } finally {
            if(instream!=null)
                instream.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, passwd.toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, new DefaultHostnameVerifier());

        httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

        // 根据默认超时限制初始化requestConfig
        this.requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout)
                .build();
    }

    /**
     * 通过Https往API post xml数据
     *
     * @param url
     *            API地址
     * @param postDataXML
     *            要提交的XML数据对象
     * @return API回包的实际数据
     * @throws IOException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */

    public String sendPost(String url, String postDataXML) {

        String result = null;
        HttpPost httpPost = new HttpPost(url);
        log.info("API，POST过去的数据是：");
        log.info(postDataXML);
        postDataXML = postDataXML.replaceAll("com.mfoyou.agent.web.utils.wx.WxWithDrawData", "xml");
        System.out.println(postDataXML);

        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        // 设置请求器的配置
        httpPost.setConfig(requestConfig);

        log.info("executing request" + httpPost.getRequestLine());

        try {
            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity, "UTF-8");

        } catch (ConnectionPoolTimeoutException e) {
            log.error("http get throw ConnectionPoolTimeoutException(wait time out)");

        } catch (ConnectTimeoutException e) {
            log.error("http get throw ConnectTimeoutException");

        } catch (SocketTimeoutException e) {
            log.error("http get throw SocketTimeoutException");

        } catch (Exception e) {
            log.error("http get throw Exception");

        } finally {
            httpPost.abort();
        }
        return result;
    }

    /**
     * 设置连接超时时间
     *
     * @param socketTimeout
     *            连接时长，默认10秒
     */
    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
        resetRequestConfig();
    }

    /**
     * 设置传输超时时间
     *
     * @param connectTimeout
     *            传输时长，默认30秒
     */
    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
        resetRequestConfig();
    }

    private void resetRequestConfig() {
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout)
                .build();
    }

    /**
     * 允许商户自己做更高级更复杂的请求器配置
     *
     * @param requestConfig
     *            设置HttpsRequest的请求器配置
     */
    public void setRequestConfig(RequestConfig requestConfig) {
        this.requestConfig = requestConfig;
    }



}